﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Util;

namespace MarkupParser
{
    public class DOM
    {
        public Node Root { get; set; }
        public Node Current { get; set; }

        public DOM(string text)
        {
            Root = Parse(text);
        }

        public static Node Parse1(string t)
        {
            int len = t.Length;
            for (int i = 0; i < len; i++)
            {
                char ichar = t[i];
                if (ichar == '<')
                {
                    int j = i + 1;
                    char jchar = t[j];
                    if (jchar == '!')
                        continue;
                    bool isClosingTag = jchar == '/';
                    if (isClosingTag) jchar = t[++j];
                    StringBuilder sb = new StringBuilder();
                    while (jchar != ' ' && jchar != '>' && jchar != '/' && j < len)
                    {
                        sb.Append(jchar);
                        jchar = t[++j];
                    }

                    Logger.WriteLine(sb.ToString());
                }

            }

            return null;
        }

        class Markup
        {
            int begin;
            int end;
            public bool HasBegin { get; set; }
            public bool HasEnd { get; set; }
            public int Begin
            {
                get { return begin; }
                set
                {
                    if (HasBegin) throw new Exception("double begin");
                    begin = value;
                    HasBegin = true;
                }
            }
            public int End
            {
                get
                {
                    return end;
                }
                set
                {
                    if (HasEnd) throw new Exception("double end");
                    end = value;
                    HasEnd = true;
                }
            }
        }

        private static bool TryToSkipScript(string t, ref int i)
        {
            string begin = t.Substring(i, 20);
            string tagEnd = "";
            bool isScript = false;
            if (begin.StartsWith("<script"))
            {
                tagEnd = "script>";
                isScript = true;
            }
            if (begin.StartsWith("<javascript"))
            {
                tagEnd = "javascript>";
                isScript = true;
            }
            if (isScript)
            {
                int newi = t.IndexOf(tagEnd, i) + tagEnd.Length;
                string script = t.Substring(i, newi - i);
                i = newi;
                return true;
            }
            return false;
        }

        public static Node Parse2(string t)
        {
            List<Markup> Markups = new List<Markup>();
            int len = t.Length;
            for (int i = 0; i < len; i++)
            {
                try
                {
                    if (t[i] == '<')
                    {
                        string text = t.Substring(i, 20);
                        if (!TryToSkipScript(t, ref i))
                        {
                            Markups.Add(new Markup { Begin = i });
                        }
                    }
                    else if (t[i] == '>')
                    {
                        string text = t.Substring(i, 20);
                        Markups.Last().End = i;
                    }
                }
                catch
                {
                    string text = t.Substring(i - 10, 20);
                    Debugger.Break();
                }
            }

            return null;
        }

        //<span class="text Gen-1-1"><span class="chapternum">1 </span>Dios, en el principio,</span></span><br
        //<span class="text Gen-1-1">creó los cielos y la tierra.</span></span><br /><span id="es-NVI-2" class
        //<span class="text Gen-1-2">las tinieblas cubrían el abismo,</span></span><br /><span class="text Gen

        public static void IsTagBegin(string t, int i)
        {
            // controlar long
            if (t[i + 1] != '/' && t[i + 1] != '!')
            {
                if (t.Substring(i, 100).StartsWith("<span class=\"text"))
                {
                    Logger.WriteLine(t.Substring(i, 100));
                    Console.ReadLine();
                }
            }
        }

        public static void IsTagEnd(string t, int i)
        {
        }

        public static Node Parse4(string t)
        {
            t = t.Replace("\n", "");
            List<Markup> Markups = new List<Markup>();
            int len = t.Length;
            for (int i = 0; i < len; i++)
            {
                if (t[i] == '<')
                    IsTagBegin(t, i);
                else if (t[i] == '>')
                    IsTagEnd(t, i);
            }

            return null;
        }

        public static Node Parse(string t)
        {
            t = t.Replace("\n", "").Replace("\t", "");
            var parts = t.Split(new char[] { '<' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            bool started = false;
            parts.ForEach(text =>
            {
                var sparts = text.Split(new char[] { '>' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                if (sparts.Count > 2)
                { }
                else
                    if (sparts.Count > 0)
                    {
                        if (started && sparts.Count > 1)
                        {
                            string content = sparts[1].Replace("&nbsp;", "").Trim();
                            if (content.Length > 1)
                            {
                                int num;
                                if (!int.TryParse(content, out num))
                                    Logger.WriteLine("[{0}]", content);
                            }
                        }

                        if (text.StartsWith("span"))
                        {
                            string tagData = sparts[0];
                            var ssparts = tagData.Split(new char[] { '=', ' ', '"' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                            if (ssparts.Count > 3)
                            {
                                if (ssparts.Contains("span") && ssparts.Contains("text"))
                                {
                                    started = true;
                                    Logger.WriteLine("{0}:", ssparts[ssparts.IndexOf("text") + 1]);
                                    Console.ReadLine();
                                }
                                //if (ssparts[0] == "span" && ssparts[1] == "class" && ssparts[2] == "text")
                                //{
                                //    started = true;
                                //}
                            }

                        }
                    }
            });
            return null;
        }
    }
}
